package com.itbaizhan.details.service.impl;

import com.itbaizhan.common.redis.dao.RedisDao;
import com.itbaizhan.common.vo.DetailsInfoVo;
import com.itbaizhan.common.vo.DetailsVo;
import com.itbaizhan.common.vo.LivegoodsResult;
import com.itbaizhan.commons.utils.JSONUtils;
import com.itbaizhan.details.mapper.DetailsMapper;
import com.itbaizhan.details.service.DetailsService;
import com.itbaizhan.pojo.House;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.concurrent.TimeUnit;

@DubboService
public class DetailsServiceImpl implements DetailsService {

    @Autowired
    private DetailsMapper detailsMapper;
    @Value("${livegoods.nginx.host}")
    private String nginxHost;
    @Value("${livegoods.redis.details}")
    private String redisKey;
    @Autowired
    private RedisDao redisDao;
    @Override
    public LivegoodsResult showDetails(Long id) {
        if (redisDao.hasKey(redisKey + ":"+id)) {
            System.out.println("走redis缓存");
            return  redisDao.get(redisKey + ":"+id);
        }
        House house = detailsMapper.selectHouseById(id);
        DetailsVo detailsVo = new DetailsVo();
        detailsVo.setId(id);
        detailsVo.setBuy(house.getBuy());
        detailsVo.setCity(house.getCity());
        detailsVo.setBuyTime(house.getBuyTime());
        detailsVo.setHouseType(house.getHouseType());
        detailsVo.setPrice(house.getPrice());
        detailsVo.setTitle(house.getTitle());
        detailsVo.setRentType(house.getRentType());

        String[] imgs = house.getImgs().split(",");
        for (int i = 0; i < imgs.length; i++) {
            imgs[i] = nginxHost + imgs[i];
        }
        detailsVo.setImgs(imgs);
        DetailsInfoVo detailsInfoVo = JSONUtils.json2object(house.getInfo(), DetailsInfoVo.class);
        detailsVo.setInfo(detailsInfoVo);
        LivegoodsResult result = LivegoodsResult.ok(detailsVo);
        //加入缓存
        redisDao.set(redisKey + ":"+id,result,7, TimeUnit.DAYS);
        System.out.println("走mysql数据库");
        return result;
    }

    @Override
    public LivegoodsResult clearHouseCache(Long id) {
        String key = redisKey + ":"+id;
        redisDao.del(key);
        return LivegoodsResult.ok("清除成功");
    }
}
